<template>
  <ItemWithLabel :label="item.label" @update:label="onChange({ label: $event })">
    <!-- 最外层选择框 -->
    <a-select
      :value="item.prop"
      :placeholder="item.placeholder"
      class="min-w-60!"
      :options="[]"
      :open="item.open"
      @dropdown-visible-change="onSelectVisibleChange(item, $event)"
      @mousedown.prevent
    >
      <template #notFoundContent>
        <!-- 选择模式 -->
        <a-space>
          <a-button type="primary" :ghost="item.dictType !== 'dict'" @click="onChange({ dictType: 'dict' })"
            >字典模式</a-button
          >
          <a-button
            type="primary"
            :ghost="item.dictType !== 'interface'"
            @click="onChange({ dictType: 'interface' })"
            >接口模式</a-button
          >
        </a-space>
      </template>
      <!-- 底部 -->
      <template #dropdownRender="{ menuNode: menu }">
        <div class="flex flex-col items-center">
          <!-- 设置 prop -->
          <div class="flex space-x-3 m-3 items-center">
            <span>prop: </span>
            <a-input
              :value="item.prop"
              allow-clear
              class="tracking-wider"
              @update:value="onChange({ prop: $event ?? void 0 })"
            ></a-input>
          </div>
          <v-nodes :vnodes="menu" />
          <!-- 分隔线 -->
          <a-divider style="margin: 4px 0" />
          <!-- 设置绑定的字典项 -->
          <template v-if="item.dictType === 'dict'">
            <a-select
              :value="item.selectDict"
              class="my-2"
              show-search
              placeholder="搜索字典项"
              style="width: 94%"
              :open="item.innerOpen"
              :filter-option="filterOption"
              @change="onChange({ selectDict: $event as string })"
              @dropdown-visible-change="onDictSelectVisibleChange(item, $event)"
            >
              <a-select-option v-for="option in dictOptions" :key="option.value">
                <div class="flex flex-col space-y-1">
                  <div>{{ option.label }}</div>
                  <div class="flex flex-col text-gray-400 text-sm">
                    <span v-for="d in dicts[option.label]" :key="d.dictLabel" class="space-x-3">
                      <span>{{ d.dictLabel }}：</span>
                      <span>{{ d.dictValue }}</span>
                    </span>
                  </div>
                </div>
              </a-select-option>
            </a-select>
            <!-- 手动输入字典项 -->
            <a-space direction="vertical" style="padding: 4px 8px">
              <a-input
                v-if="item.dicts.length"
                :value="item.dictName"
                class="tracking-widest!"
                allow-clear
                placeholder="请输入字段名称"
                @update:value="onChange({ dictName: $event ?? void 0 })"
              ></a-input>
              <!-- 字典项 -->
              <div
                v-for="(d, index2) in item.dicts as DictItem[]"
                :key="(d.dictValue as any).value"
                class="flex items-center space-x-3"
              >
                <a-input v-model:value="d.dictLabel" placeholder="标签" />
                <a-input v-model:value="d.dictValue" placeholder="值" />
                <CloseCircleFilled
                  :style="{ color: '#ff3541', cursor: 'pointer' }"
                  @click="removeDictItem(item, index2)"
                />
              </div>
              <a-button type="text" @click="addDictItem(item)">
                <template #icon>
                  <PlusOutlined />
                </template>
                添加字典项 （如果需要）
              </a-button>
            </a-space>
          </template>
          <div v-else class="text-center my-2">已选择接口模式, 将会自动添加相关代码</div>
        </div>
      </template>
    </a-select>
  </ItemWithLabel>
</template>

<script setup lang="ts" name="editable-select">
import { EditItem } from '@/form'
import { useConfigStore } from '@/store'
import type { SelectProps } from 'ant-design-vue'
import { PlusOutlined, CloseCircleFilled } from '@ant-design/icons-vue'
import ItemWithLabel from './with-label.vue'

const props = defineProps<{
  item: EditItem.Select
}>()

const emit = defineEmits<{
  (event: 'update:item', data: EditItem.Select)
}>()

const VNodes = defineComponent({
  props: {
    vnodes: {
      type: Object,
      required: true
    }
  },
  render() {
    return this.vnodes
  }
})

const onChange = (domain: { [k in keyof Partial<EditItem.Select>]: EditItem.Select[k] }) => {
  emit('update:item', { ...props.item, ...domain })
}

const { dicts } = useConfigStore()
// 字段搜索框的下拉框是否已显示，未显示状态下，外层select的popover 才应该消失，
const dictOptions = ref<SelectProps['options']>(
  Object.keys(dicts).map((dictName) => {
    return { label: dictName, value: dictName }
  })
)
const filterOption = (input: string, { key, value }: any) => {
  const isMatchedLabel = value.toLowerCase().indexOf(input.toLowerCase()) >= 0
  const isMatchedDicts = dicts[key as string].some((item) => item.dictLabel.includes(input))
  return isMatchedLabel || isMatchedDicts
}

const addDictItem = (item: EditItem.Select) => {
  item.dicts?.push({ dictLabel: ref('') as any, dictValue: ref('') as any })
}
const removeDictItem = (item: EditItem.Select, index: number) => {
  item.dicts?.splice(index, 1)
}

const onSelectVisibleChange = (item: EditItem.Select, visible: boolean) => {
  if (!visible && !item.innerOpen) {
    item.open = false
    return
  }
  item.open = true
}
const onDictSelectVisibleChange = (item: EditItem.Select, visible: boolean) => {
  item.innerOpen = visible
}
</script>

<style scoped></style>
